// pages/login/login.js
import WxValidate from '../../utils/WxValidate.js'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hiddenName: true,
    
    code:'',
    avatarUrl:'',
    nickName:'',
    tel:"",
    pwd:'',
  },
  // 点击忘记密码
  forgetClick(){
   wx.navigateTo({
     url: '../forget/forget',
   }) 
  },
  toggleShow: function () {
    this.setData({
      hiddenName: !this.data.hiddenName
    })
  },
  sign: function () {
    var that = this
    wx.navigateTo({
      url: '../sign/sign?code=' + that.data.code + "&avatarUrl=" + that.data.avatarUrl + "&nickName=" + that.data.nickName
    })
  },
  /**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    let that = this;
    if (options.avatarUrl){
      that.setData({
        avatarUrl: options.avatarUrl,
        nickName: options.nickName
      })
    }
  },
  onShow: function () {
    let that = this;
    
  },
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },
  formSubmit(e) {
    var that = this;
    let form = e.detail.value;
    if (!form.username){
     wx.showModal({
       title: '提示',
       content: '请输入账号',
     })
     return
    }
    console.log(form.password)
    if (!form.password) {
      wx.showModal({
        title: '提示',
        content: '请输入密码',
      })
      return
    }
    wx.login({
      success: function (res) {
        let postData = {
          code:res.code,
          wx_avatar: that.data.avatarUrl,
          wx_nickname: that.data.nickName,
          ...form
        }
        app.post("/login/login", "post", postData).then(res => {
          if (res.statusCode == "302") {
            wx.showModal({
              title: '提示',
              content: '登录账号或密码错误',
              showCancel: false,
              confirmText: '是否还未注册？去注册',
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击了“返回授权”')
                }
              }
            })
          } else {
            wx.showToast({
              title: '登录成功',
            })
            setTimeout(function(){
              wx.switchTab({
                url: '../index/index'
              })
            },500)
           
            wx.setStorageSync("token", res.token);
            wx.setStorageSync("tel", that.data.tel);
          }

        }, err => {
          wx.showModal({
            title: '提示',
            content: '登录账号或密码错误',
            showCancel: false,
            confirmText: '是否还未注册？去注册',
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击了“返回授权”')
              }
            }
          })

        })
      }
    })
   
    
    
  },
  
})